//
//  CS_Page_RadioView.m
//  Pods
//
//  Created by 网新中研 on 2017/7/18.
//
//

#import "CS_Page_RadioView.h"

#define ICON_HEIGHT 20.0

@class CS_Radio_ItemView;

typedef void(^ClickHandlerBlock)(CS_Radio_ItemView *radioItemView);

@interface CS_Radio_ItemView()

@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UILabel *lableView;
@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, strong) NSString *itemName;

@property (nonatomic, copy) ClickHandlerBlock selectHandler;

@property (nonatomic, strong) UIButton *button;

@end

@implementation CS_Radio_ItemView

/**
 * 图标
 */
static NSMutableDictionary *_iconDic;

/**
 * 加载textfield
 */
+(void)loadImageWithType:(CSRadioViewType)key value:(UIImage *)image{
    
    if(_iconDic == nil){
        _iconDic = [NSMutableDictionary new];
    }
    
    if (image == nil) {
        return;
    }
    
    [_iconDic setObject:image forKey:@(key)];
}

+(instancetype)radio_ItemView:(NSString *)title cellheight:(CGFloat)cellHeight{
    
    CS_Radio_ItemView *radio_ItemView = [CS_Radio_ItemView new];
    radio_ItemView.lableView.text = title;
    radio_ItemView.itemName = title;
    radio_ItemView.cellHeight = cellHeight;
    [radio_ItemView layoutView];
    return radio_ItemView;
    
}

+(instancetype)radio_ItemViewWithModel:(CSSelectableModel *)model cellheight:(CGFloat)cellHeight{
    
    CS_Radio_ItemView *radio_ItemView = [CS_Radio_ItemView new];
    radio_ItemView.model = model;
    radio_ItemView.lableView.text = model.content;
    radio_ItemView.itemName = model.content;
    radio_ItemView.cellHeight = cellHeight;
    [radio_ItemView layoutView];
    return radio_ItemView;
    
}



-(CGFloat)estimateWidth:(NSString *)content{
    
    return [self estimateWith:content font:self.lableView.font height:_cellHeight];
    
}

-(void)layoutView{
    
    CGFloat primaryY = (_cellHeight - ICON_HEIGHT) / 2.0;
    
    self.iconImageView.frame = CGRectMake(5, primaryY, ICON_HEIGHT, ICON_HEIGHT);
    CGFloat needWidth = [self estimateWidth:_itemName];
    self.lableView.frame = CGRectMake(ICON_HEIGHT + 10, 0, needWidth, _cellHeight);
    [self addSubview:self.iconImageView];
    [self addSubview:self.lableView];
    self.frame = CGRectMake(0, 0, ICON_HEIGHT + 10.0 + needWidth, _cellHeight);
    self.button.frame = self.frame;
    [self addSubview:self.button];
    
}

/**
 * 重新设置大小
 */
-(void)reSizeView{
    
    CGFloat needWidth = [self estimateWidth:_itemName];
    CGFloat needHeight = _cellHeight;
    
    if (needWidth +  ICON_HEIGHT + 10 > self.frame.size.width) {
        
        needWidth = self.frame.size.width - (ICON_HEIGHT + 10);
        needHeight = [self estimateHeight:self.lableView.text font:self.lableView.font width:needWidth];
        needHeight += 10;
    }
    
    self.lableView.frame = CGRectMake(ICON_HEIGHT + 10, 0, needWidth, needHeight);
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, ICON_HEIGHT + 10.0 + needWidth, needHeight);
    self.button.frame = CGRectMake(0, 0, ICON_HEIGHT + 10.0 + needWidth, needHeight);
    
}

-(void)setIsEnabled:(BOOL)isEnabled{
    
    _isEnabled = isEnabled;
    
    if (_isEnabled) {
        
        self.selected = self.selected;
        self.model.isSelected = self.selected;
        
    }else{
        
        self.backgroundColor = [UIColor clearColor];
        
        self.lableView.textColor = [UIColor colorFromHexCode:@"b4b4b4"];
        
        if (self.disableSelectImage) {
            
            self.iconImageView.image = self.disableSelectImage;
            
        }else{
            
            self.iconImageView.image = self.unSelectedImage;
            
            if (!self.iconImageView.image) {
                
                //不使能
                self.iconImageView.image = [CSPageEngine getImageWithKey:KEY_ICON_CHECK_DISABLE];
                
            }
        }
    }
}

-(void)selectClick{
    
    if (self.selectHandler != nil) {
        self.selectHandler(self);
    }
    
}

-(void)setSelected:(BOOL)selected{
    
    _selected = selected;
    
    _model.isSelected = selected;
    
    if (selected) {
        
        _iconImageView.image = self.selectedImage;
        
        if (!_iconImageView.image) {
            //选中
            _iconImageView.image = [CSPageEngine getImageWithKey:KEY_ICON_RADIO_YES];
        }
        
        //如果是新风格
        if (self.isStyleNew) {
            
            self.backgroundColor = COLOR_THEME;
            self.lableView.textColor = COLOR_WHITE;
            
        }
        
    }else{
        
        _iconImageView.image = self.unSelectedImage;
        
        if (!_iconImageView.image) {
            //不选中
            _iconImageView.image = [CSPageEngine getImageWithKey:KEY_ICON_RADIO_NO];
        }
        
        //如果是新风格
        if (self.isStyleNew) {
            
            self.backgroundColor = [UIColor clearColor];
            self.lableView.textColor = COLOR_TEXT_2;
            
        }
    }
    
}

-(UIImageView *)iconImageView{
    if (_iconImageView == nil) {
        _iconImageView = [[UIImageView alloc] initWithImage:[CSPageEngine getImageWithKey:KEY_ICON_RADIO_YES]];
    }
    return _iconImageView;
}

-(UILabel *)lableView{
    if (_lableView == nil) {
        _lableView = [UILabel new];
        _lableView.font = [UIFont systemFontOfSize:FONT_SIZE_1];
        _lableView.textColor = COLOR_TEXT_2;
        _lableView.numberOfLines = 0;
    }
    return _lableView;
}

-(UIButton *)button{
    if (_button == nil) {
        _button = [[UIButton alloc]init];
        [_button addTarget:self action:@selector(selectClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}

@end

@interface CS_Page_RadioView()

/**
 * 单选标题
 */
@property (nonatomic, strong) NSString *title;

@property (nonatomic, strong) NSArray *radioTitles;

/**
 * 按钮选项
 */
@property (nonatomic, strong) NSMutableArray *butonArrays;

/**
 * 是否是第一次
 */
@property (nonatomic, assign) BOOL isFirstTime;

/**
 * 选中处理
 */
@property (nonatomic, copy) RadioButtonClick selectHandler;

@property (nonatomic, copy) RadioSelectableButtonClick selectableHandler;

@property (nonatomic, strong) UIView *seperatorLine;

@property (nonatomic, assign) BOOL isNoDefaultValue;

@end

#define LEFT_VIEW_WIDTH 80.0
#define ITEM_MARGIN 10.0
#define ITEM_HEIGHT 30.0
#define CELL_LEFT_MARGIN CELL_EDIT_RIGHT_MARGIN

@implementation CS_Page_RadioView

-(NSInteger)viewType{
    return CSViewType_PageRadioView;
}

+(instancetype)pageRadioViewWithNoDefaultSelected:(NSString *)title items:(NSArray *)array selectedHandler:(RadioButtonClick)selectHandler{

    CS_Page_RadioView *radioButtonView = [CS_Page_RadioView new];
    radioButtonView.title = title;
    
    NSMutableArray *mutableArray = [NSMutableArray new];
    for (int i = 0; i < array.count; i++) {
        id titleObj = [array objectAtIndex:i];
        if ([titleObj isKindOfClass:[CSSelectableModel class]]) {
            CSSelectableModel *model  = (CSSelectableModel *)titleObj;
            [mutableArray addObject:model.content];
        }else if ([titleObj isKindOfClass:[NSString class]]){
            [mutableArray addObject:titleObj];
        }
    }
    radioButtonView.radioTitles = mutableArray;
    radioButtonView.isFirstTime = YES;
    radioButtonView.textAlignment = NSTextAlignmentLeft;//默认标题左对齐
    radioButtonView.selectHandler = selectHandler;
    radioButtonView.isNoDefaultValue = YES;
    
    return radioButtonView;
    
}

+(instancetype)pageRadioView:(NSString *)title items:(NSArray *)array selectedHandler:(RadioButtonClick)selectHandler{
    
    CS_Page_RadioView *radioButtonView = [CS_Page_RadioView new];
    radioButtonView.title = title;
    
    NSMutableArray *mutableArray = [NSMutableArray new];
    for (int i = 0; i < array.count; i++) {
        id titleObj = [array objectAtIndex:i];
        if ([titleObj isKindOfClass:[CSSelectableModel class]]) {
            CSSelectableModel *model  = (CSSelectableModel *)titleObj;
            [mutableArray addObject:model.content];
        }else if ([titleObj isKindOfClass:[NSString class]]){
            [mutableArray addObject:titleObj];
        }
    }
    radioButtonView.radioTitles = mutableArray;
    radioButtonView.isFirstTime = YES;
    radioButtonView.textAlignment = NSTextAlignmentLeft;//默认标题左对齐
    radioButtonView.selectedIndex = 0;
    radioButtonView.selectHandler = selectHandler;
    
    return radioButtonView;
    
}

+(instancetype)pageRadioView:(NSString *)title items:(NSArray *)array selectableHandler:(RadioSelectableButtonClick)selectableHandler{
    
    if (array == nil || array.count <= 0 || ![[array objectAtIndex:0] isKindOfClass:[CSSelectableModel class]]) {
        return nil;
    }
    
    CS_Page_RadioView *radioButtonView = [CS_Page_RadioView new];
    radioButtonView.title = title;
    radioButtonView.radioSelectableModels = [NSMutableArray new];
    
    for (int i = 0; i < array.count; i++) {
        
        CSSelectableModel *selectableModel = [array objectAtIndex:i];
        [radioButtonView.radioSelectableModels addObject:selectableModel];
        
        if (selectableModel.subItems != nil && selectableModel.subItems.count > 0) {
            
            if ([[selectableModel.subItems objectAtIndex:i] isKindOfClass:[CSSelectableModel class]]) {
                
                //如果子项也是CSSelectableModel类型
                [radioButtonView.radioSelectableModels addObject:[selectableModel.subItems objectAtIndex:i]];
                
            }
        }
    }
    
    radioButtonView.isFirstTime = YES;
    radioButtonView.textAlignment = NSTextAlignmentLeft;//默认标题左对齐
    radioButtonView.selectedIndex = 0;
    radioButtonView.selectableHandler = selectableHandler;
    
    return radioButtonView;
    
}



-(CGFloat)layoutView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    if (self.radioSelectableModels != nil) {
        
        return [self layoutNewStyleView:superView primaryY:primaryY];
    }
    
    //右侧剩余宽度
    CGFloat rightWidth = kWindowW;
    
    //初始X值
    CGFloat primaryX = self.leftMargin;
    
    //内部初始Y轴坐标
    CGFloat primaryInternalY = ITEM_MARGIN;
    
    //总高度
    CGFloat totalHeight = ITEM_MARGIN;
    
    //标准宽度
    CGFloat standardWidth = (rightWidth - ITEM_MARGIN * 3 - self.leftMargin - self.rightMargin) / 4.0;
    
    //剩余宽度
    CGFloat restWidth = rightWidth - self.leftMargin;
    
    //最终宽度
    CGFloat finalWidth = standardWidth;
    
    if (![self isNullOrEmpty:self.title]) {
        
        self.descriptionLabel.text = [NSString stringWithFormat:@"%@", self.title];
        self.descriptionLabel.frame = CGRectMake(self.leftMargin, ITEM_MARGIN * 3, kWindowW - self.leftMargin - self.rightMargin, ITEM_HEIGHT + ITEM_MARGIN);
        self.descriptionLabel.textAlignment = self.textAlignment;
        self.descriptionLabel.textColor = [UIColor colorFromHexCode:@"#666666"];
        [self addSubview:self.descriptionLabel];
        
        primaryInternalY += ITEM_HEIGHT + 4 * ITEM_MARGIN;
        
        if (self.radioTitles.count > 0) {
            totalHeight += ITEM_HEIGHT + ITEM_MARGIN;
        }
    }
    
   self.butonArrays = [NSMutableArray new];
    
    WS(weakSelf);
    
    for (int i = 0; i < self.radioTitles.count; i++) {
        
        //按钮
        NSString *title = [self.radioTitles objectAtIndex:i];
        CS_Radio_ItemView *radioButton = [CS_Radio_ItemView radio_ItemView:title cellheight:ITEM_HEIGHT];
        radioButton.selectHandler = ^(CS_Radio_ItemView *radioItemView) {
            [weakSelf select:radioItemView];
        };
        radioButton.selected = NO;
        
        //计算所需要的最小宽度并获得最终宽度（宽度总是标准行的整数倍）
        CGFloat needWidth = radioButton.frame.size.width;
        finalWidth = needWidth;
        
        //计算坐标
        if (finalWidth + self.rightMargin <= restWidth) {
            radioButton.frame = CGRectMake(kWindowW - restWidth, primaryInternalY, finalWidth, ITEM_HEIGHT);
            restWidth = restWidth - finalWidth - ITEM_MARGIN;
        }else{//另起一行
            primaryInternalY += ITEM_MARGIN + ITEM_HEIGHT;
            radioButton.frame = CGRectMake(primaryX, primaryInternalY, finalWidth, ITEM_HEIGHT);
            totalHeight += ITEM_HEIGHT + ITEM_MARGIN;
            restWidth = rightWidth - finalWidth - ITEM_MARGIN - self.leftMargin;
        }
        
        [self.butonArrays addObject:radioButton];
        [self addSubview:radioButton];
    }
    
    totalHeight += 2 * ITEM_MARGIN;
    
    totalHeight += 1;
    
    //自定义大小
    self.frame = CGRectMake(0, primaryY, kWindowW, totalHeight);
    [superView addSubview:self];
    
    if (!self.isNoDefaultValue) {
        
        //默认选中
        if (self.butonArrays.count>0) {
            [self selectWithSelectIndex:_selectedIndex];
        }
        
    }else{
        
    }
    
    self.isFirstTime = NO;
    
    return [super layoutView:superView primaryY:primaryY + totalHeight];
}

-(CGFloat)layoutNewStyleView:(UIView *)superView primaryY:(CGFloat)primaryY{
    
    //右侧剩余宽度
    CGFloat rightWidth = kWindowW;
    
    //初始X值
    CGFloat primaryX = self.leftMargin;
    
    //内部初始Y轴坐标
    CGFloat primaryInternalY = ITEM_MARGIN;
    
    //总高度
    CGFloat totalHeight = ITEM_MARGIN;
    
    //标准宽度
    CGFloat standardWidth = (rightWidth - ITEM_MARGIN * 3 - self.leftMargin - self.rightMargin) / 4.0;
    
    //剩余宽度
    CGFloat restWidth = rightWidth - self.leftMargin;
    
    //最终宽度
    CGFloat finalWidth = standardWidth;
    
    if (![self isNullOrEmpty:self.title]) {
        
        self.descriptionLabel.text = [NSString stringWithFormat:@"%@", self.title];
        self.descriptionLabel.frame = CGRectMake(self.leftMargin, ITEM_MARGIN * 3, kWindowW - self.leftMargin - self.rightMargin, ITEM_HEIGHT + ITEM_MARGIN);
        self.descriptionLabel.textAlignment = self.textAlignment;
        self.descriptionLabel.textColor = [UIColor colorFromHexCode:@"#666666"];
        [self addSubview:self.descriptionLabel];
        
        primaryInternalY += ITEM_HEIGHT + 4 * ITEM_MARGIN;
        
        if (self.radioTitles.count > 0) {
            totalHeight += ITEM_HEIGHT + ITEM_MARGIN;
        }
    }
    
    self.butonArrays = [NSMutableArray new];
    
    WS(weakSelf);
    
    for (int i = 0; i < self.radioSelectableModels.count; i++) {
        
        //按钮
        CSSelectableModel *selectableModel = [self.radioSelectableModels objectAtIndex:i];
        CS_Radio_ItemView *radioButton = [CS_Radio_ItemView radio_ItemViewWithModel:selectableModel cellheight:ITEM_HEIGHT];
        radioButton.isStyleNew = YES;
        radioButton.isEnabled = selectableModel.isEnabled;
        radioButton.layer.cornerRadius = 2;
        radioButton.layer.masksToBounds = YES;
        radioButton.disableSelectImage = [CSPageEngine getImageWithKey:KEY_ICON_CHECK_DISABLE];
        if (self.isMulityEnable) {
            radioButton.selectedImage = [CSPageEngine getImageWithKey:KEY_ICON_CHECK_YES];
        }
        radioButton.selectHandler = ^(CS_Radio_ItemView *radioItemView) {
            [weakSelf select:radioItemView];
        };
        
        //计算所需要的最小宽度并获得最终宽度（宽度总是标准行的整数倍）
        CGFloat needWidth = radioButton.frame.size.width;
        finalWidth = needWidth + 10;
        
        //计算坐标
        if (finalWidth + self.rightMargin <= restWidth) {
            radioButton.frame = CGRectMake(kWindowW - restWidth, primaryInternalY, finalWidth, ITEM_HEIGHT);
            restWidth = restWidth - finalWidth - ITEM_MARGIN;
        }else if (finalWidth > kWindowW - self.leftMargin - self.rightMargin){//当选项文字长度超过允许行宽
            
            //第一行
            if (restWidth == kWindowW - self.leftMargin) {
                
                CGFloat needHeight = [self estimateHeight:selectableModel.content font:radioButton.lableView.font width:kWindowW - self.leftMargin - self.rightMargin];
                needHeight += 15;
                if (needHeight < ITEM_HEIGHT) {
                    needHeight = ITEM_HEIGHT;
                }
                radioButton.frame = CGRectMake(primaryX, primaryInternalY, kWindowW - self.leftMargin - self.rightMargin, needHeight);
                [radioButton reSizeView];
                
                primaryInternalY = ITEM_MARGIN + needHeight;
                totalHeight += needHeight + ITEM_MARGIN;
                
            }else{
                
                if (restWidth != -1231241) {
                    primaryInternalY += ITEM_MARGIN + ITEM_HEIGHT;
                }
                
                CGFloat needHeight = [self estimateHeight:selectableModel.content font:radioButton.lableView.font width:kWindowW - self.leftMargin - self.rightMargin];
                needHeight += 15;
                if (needHeight < ITEM_HEIGHT) {
                    needHeight = ITEM_HEIGHT;
                }
                radioButton.frame = CGRectMake(primaryX, primaryInternalY, kWindowW - self.leftMargin - self.rightMargin, needHeight);
                [radioButton reSizeView];
                
                primaryInternalY += ITEM_MARGIN + needHeight;
                totalHeight += needHeight + ITEM_MARGIN;
            }
            
            restWidth = -1231241;
            
        }else{//另起一行
            if (restWidth != -1231241) {
                primaryInternalY += ITEM_MARGIN + ITEM_HEIGHT;
            }
            radioButton.frame = CGRectMake(primaryX, primaryInternalY, finalWidth, ITEM_HEIGHT);
            totalHeight += ITEM_HEIGHT + ITEM_MARGIN;
            restWidth = kWindowW - finalWidth - ITEM_MARGIN - self.leftMargin;
        }
        
        [self.butonArrays addObject:radioButton];
        [self addSubview:radioButton];
    }
    
    totalHeight += 2 * ITEM_MARGIN;
    
    totalHeight += 1;
    
    //自定义大小
    self.frame = CGRectMake(0, primaryY, kWindowW, totalHeight);
    [superView addSubview:self];
    
    //默认选中
    if (self.butonArrays.count>0 && !self.isMulityEnable) {
        [self selectWithSelectIndex:_selectedIndex];
    }
    
    self.isFirstTime = NO;
    
    return primaryY + totalHeight + 10;
}


-(void)select:(id)sender{
    NSInteger clickIndex = [self.butonArrays indexOfObject:sender];
    [self selectWithSelectIndex:clickIndex];
}

-(void)selectWithSelectIndex:(NSInteger)index{
    
    //默认选中
    if (self.butonArrays.count<=0) {
        return;
    }
    
    if (index < 0 || index > self.butonArrays.count) {
        return;
    }
    
    CS_Radio_ItemView *selectedButton = (CS_Radio_ItemView *)[self.butonArrays objectAtIndex:index];
    _selectedIndex = index;
    
    if (self.isMulityEnable) {
        if (selectedButton.isEnabled) {
            [selectedButton setSelected:!selectedButton.selected];
        }
        if (self.selectHandler) {
            self.selectHandler(index);
        }
        
        if (self.selectableHandler) {
            self.selectableHandler([self.radioSelectableModels objectAtIndex:index]);
        }
    }else{
        for (int i = 0 ; i < self.butonArrays.count ; i++) {
            CS_Radio_ItemView *button  = (CS_Radio_ItemView *)[self.butonArrays objectAtIndex:i];
            [button setSelected:NO];
        }
        
        [selectedButton setSelected:YES];
        
        if (self.selectHandler) {
            self.selectHandler(index);
        }
        
        if (self.selectableHandler) {
            self.selectableHandler([self.radioSelectableModels objectAtIndex:index]);
        }
    }
    
}

-(NSString *)value{
    
    return [NSString stringWithFormat:@"%ld", (long)_selectedIndex];
}

-(void)setValue:(NSString *)value{
    if (value == nil
        || [value isEqualToString:@""]) {
        return;
    }
    
    _selectedIndex = [value intValue];
    
    UIButton *button = [self.butonArrays objectAtIndex:_selectedIndex];
    [self select:button];
}

- (UIView *)seperatorLine {
    if(_seperatorLine == nil) {
        _seperatorLine = [[UIView alloc] init];
        STYLE_SEPERATOR_LINE(_seperatorLine);
    }
    return _seperatorLine;
}

-(void)reset{
    [self setValue:@"0"];
}


@end
